<template>
  <div class="power-source">
    <el-row>
      <el-col :span="12">
        <fieldset>
          <legend>总电源状态:</legend>
          <div class="form-content">
            <div class="form-item">
              <label for="">U<sub>a</sub>：</label>
              <el-input v-model="ua" disabled></el-input>
              <span class="unit">V</span>
            </div>
            <div class="form-item">
              <label for="">U<sub>b</sub>：</label>
              <el-input v-model="ub" disabled></el-input>
              <span class="unit">V</span>
            </div>
            <div class="form-item">
              <label for="">U<sub>c</sub>：</label>
              <el-input v-model="uc" disabled></el-input>
              <span class="unit">V</span>
            </div>
            <div class="form-item">
              <label for="">I<sub>a</sub>：</label>
              <el-input v-model="ia" disabled></el-input>
              <span class="unit">A</span>
            </div>
            <div class="form-item">
              <label for="">I<sub>b</sub>：</label>
              <el-input v-model="ib" disabled></el-input>
              <span class="unit">A</span>
            </div>
            <div class="form-item">
              <label for="">I<sub>c</sub>：</label>
              <el-input v-model="ic" disabled></el-input>
              <span class="unit">A</span>
            </div>
          </div>
        </fieldset>
        <fieldset>
          <legend>相位:</legend>
          <div class="form-content">
            <div class="form-item">
              <label for="">φ<sub>a</sub>：</label>
              <el-input v-model="φa" disabled></el-input>
              <span class="unit">°</span>
            </div>
            <div class="form-item">
              <label for="">φ<sub>b</sub>：</label>
              <el-input v-model="φb" disabled></el-input>
              <span class="unit">°</span>
            </div>
            <div class="form-item">
              <label for="">φ<sub>c</sub>：</label>
              <el-input v-model="φc" disabled></el-input>
              <span class="unit">°</span>
            </div>
            <div class="form-item">
              <label for="">角度：</label>
              <el-input v-model="angle" @input="changePf"></el-input>
              <span class="unit">°</span>
            </div>
            <div class="form-item">
              <label for="">Pf：</label>
              <el-input v-model="pf" @input="changeAngle"></el-input>
              <span class="unit">
                <el-select
                  v-model="pfUnit"
                  placeholder="Select"
                  style="width: 60px"
                  @change="changeAngleUnit"
                >
                  <el-option label="L" value="L">L</el-option>
                  <el-option label="C" value="C">C</el-option>
                </el-select>
              </span>
            </div>
            <div class="form-item"></div>
          </div>
        </fieldset>
        <fieldset>
          <legend>电源报警状态:</legend>
          <div class="alarm-group">
            <!-- v-html="$addSub(item)" :class="{ isWarm: powerAlarmArray.includes(item.toLowerCase()) }" -->
            <div
              class="alarm-item"
              v-for="(item, index) in alarmItemList"
              :key="index"
              :class="{ isWarm: powerAlarmArray.includes(item.toLowerCase()) }"
            >
              {{ item }}
            </div>
          </div>
        </fieldset>
      </el-col>
      <el-col :span="12">
        <div class="form-content" style="width: 650px">
          <div class="form-item">
            <label for="">电流：</label>
            <el-input v-model="i"></el-input>
            <!-- <el-select v-model="i" class="m-2" style="width: 100px">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select> -->
            <span class="unit">A</span>
          </div>
        </div>
        <fieldset>
          <legend>控制:</legend>
          <div class="ps-control">
            <el-button @click="openPower(0)">关闭电源</el-button>
            <el-button @click="openPower(1)">打开电源</el-button>
            <el-button @click="setI">设置电流</el-button>
            <el-button @click="setP">设置角度</el-button>
            <el-button @click="setP">设置Pf</el-button>
          </div>
        </fieldset>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeMount, onUnmounted } from "vue";
import websocketSocket from "@/api/socket";
import { useAppStore } from "@/stores";
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";
import {
  sourceSetOnOff,
  sourceSetIRange,
  sourceSetF,
  sourceSetPAll,
  sourceState,
} from "@/api/source.js";
const useApp = useAppStore();
let { powerEle } = storeToRefs(useApp);

const alarmItemList = ["Ua", "Ub", "Uc", "Ia", "Ib", "Ic"];
const i = ref("1.50");
const pf = ref("1.00");
const angle = ref(0);
const powerAlarmArray = ref([]);
const ua = ref();
const ub = ref();
const uc = ref();
const ia = ref();
const ib = ref();
const ic = ref();
const φa = ref();
const φb = ref();
const φc = ref();
const pfUnit = ref("L");
const options = [
  {
    value: "0.00",
    label: "0.00",
  },
  {
    value: "1.00",
    label: "1.00",
  },
  {
    value: "1.50",
    label: "1.50",
  },
  {
    value: "2.00",
    label: "2.00",
  },
  {
    value: "5.00",
    label: "5.00",
  },
];
// 设置初始化，防止刷新时恢复默认
onBeforeMount(() => {
  //websockt 模块
  websocketSocket.init(wsReceive); //开启socket
});
// ws接收消息
const wsReceive = (result) => {
  // console.log(result);
  // 接收数据后回调
  let { code, data } = result;
  if (code) {
    let phase = JSON.parse(data.phase);
    let source = JSON.parse(data.source);
    if (phase) {
      φa.value = Number(phase.pia).toFixed(2);
      φb.value = Number(phase.pib).toFixed(2);
      φc.value = Number(phase.pic).toFixed(2);
    }
    if (source) {
      ua.value = (
        (Number(source.state.ua) * Number(source.state.uar)) /
        100
      ).toFixed(2);
      ub.value = (
        (Number(source.state.ub) * Number(source.state.ubr)) /
        100
      ).toFixed(2);
      uc.value = (
        (Number(source.state.uc) * Number(source.state.ucr)) /
        100
      ).toFixed(2);
      ia.value = (
        (Number(source.state.ia) * Number(source.state.iar)) /
        100
      ).toFixed(2);
      ib.value = (
        (Number(source.state.ib) * Number(source.state.ibr)) /
        100
      ).toFixed(2);
      ic.value = (
        (Number(source.state.ic) * Number(source.state.icr)) /
        100
      ).toFixed(2);
      powerAlarmArray.value = Object.keys(source.alarm);
      powerEle.value = data;
    }
  }
};
onUnmounted(() => {
  websocketSocket.close();
});
onMounted(() => {
  // init(); //设备报警状态
});
//开关电源
const openPower = async (state) => {
  let parm = {
    state,
    i: i.value,
  };
  await sourceSetOnOff(parm)
    .then((res) => {
      // console.log(res);
      ElMessage({
        showClose: true,
        message: "设置成功",
        type: "success",
      });
    })
    .catch(() => {
      // console.log(res);
      ElMessage({
        showClose: true,
        message: "设置失败",
        type: "warning",
      });
    });
};
//设置电流
const setI = async () => {
  let eleI = (Number(i.value) / 5) * 100;
  const params = {
    PElectricityRange: 0,
    rangeElectricity: eleI,
  };
  await sourceSetIRange(params)
    .then((res) => {
      // console.log(res);
      ElMessage({
        showClose: true,
        message: "设置成功",
        type: "success",
      });
    })
    .catch(() => {
      // console.log(res);
      ElMessage({
        showClose: true,
        message: "设置失败",
        type: "warning",
      });
    });
};
//设置角度
const setP = async () => {
  let newAngle = [];
  let parm1 = Number(angle.value);
  let parm2 = 120 + parm1;
  let parm3 = 240 + parm1;
  newAngle[0] = parm1 > 360 ? parm1 - 360 : parm1;
  newAngle[1] = parm2 > 360 ? parm2 - 360 : parm2;
  newAngle[2] = parm3 > 360 ? parm3 - 360 : parm3;
  const params = {
    angle: newAngle,
  };
  await sourceSetPAll(params)
    .then((res) => {
      // console.log(res);
      ElMessage({
        showClose: true,
        message: "设置成功",
        type: "success",
      });
    })
    .catch(() => {
      // console.log(res);
      ElMessage({
        showClose: true,
        message: "设置失败",
        type: "warning",
      });
    });
};
const changePf = () => {
  let radian = 180 / Math.PI;
  let newPf = Math.cos(angle.value / radian);
  pf.value = newPf.toFixed(2);
};
const changeAngle = () => {
  if (pf.value) {
    if (parseInt(pf.value) > 1) pf.value = 1;
    if (parseInt(pf.value) < 0) pf.value = 0;
    let newAngle = Math.acos(pf.value);
    newAngle = ((newAngle * 180) / Math.PI).toFixed(2);
    angle.value = newAngle;
  }
};
const changeAngleUnit = () => {
  if (pf.value) {
    if (parseInt(pf.value) < 0) pf.value = 0;
    let newAngle = Math.acos(pf.value);
    newAngle = ((newAngle * 180) / Math.PI).toFixed(2);
    angle.value = newAngle;

    if (pfUnit.value === "C") angle.value = 360 - angle.value;
    else angle.value = newAngle;
  }
};
// 电源状态，设备报警状态、
const init = async () => {
  await sourceState()
    .then((res) => {
      // console.log(res);
      if (res.data) {
        powerAlarmArray.value = res.data.alarm;
        ua.value = res.data.state.ua;
        ub.value = res.data.state.ub;
        uc.value = res.data.state.uc;
        ia.value = res.data.state.ia;
        ib.value = res.data.state.ib;
        ic.value = res.data.state.ic;
        φa.value = res.data.state.φa;
        φb.value = res.data.state.φb;
        φc.value = res.data.state.φc;
        angle.value = res.data.state.angle;
        pf.value = res.data.state.pf;
      }
    })
    .catch((err) => {
      console.log(err);
    });
};
</script>

<style lang="scss" scoped>
//功率源
.power-source {
  .form-content {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    align-items: center;
    .form-item {
      display: flex;
      align-items: center;
      width: 33.33%;
      padding: 10px 35px;
      .el-input {
        width: 100px;
      }
      label {
        width: 55px;
      }
    }
  }
  // 电源报警状态
  .alarm-group {
    display: flex;
    flex-wrap: wrap;
    width: 300px;
    margin: 0 auto;
    .alarm-item {
      width: 50px;
      margin: 20px 20px;
      height: 1.875rem;
      border: 0.0625rem /* 1/16 */ double #e3e3e3;
      border-radius: 0.3125rem /* 5/16 */;
      text-align: center;
      line-height: 1.875rem;
      font-weight: 700;
      color: #fff;
      background-color: #67c23a;
      cursor: pointer;
    }
  }
  // 控制按钮
  .ps-control {
    width: 500px;
    margin: 0 auto;
    .el-button {
      width: 200px;
      height: 50px;
      margin: 10px;
    }
  }
}
.isWarm {
  background-color: red !important;
}
</style>
